package com.xbongbong.rule.symbol;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.saas.constant.StringConstant;
import org.springframework.util.StringUtils;
import com.xbongbong.rule.symbol.base.AbstractSymbol;

import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 为空判断(值为空或数组为空)
 * 适用类型:除关联数据外所有类型
 *
 * @author zheng.li
 **/
public class EmptySymbol extends AbstractSymbol {

    @Override
    public boolean operation() {
        if (Objects.equals(fieldType, FieldTypeEnum.ADDRESS.getType())) {
            //地址
            if (attr.contains(FieldTypeEnum.SUB_FORM.getEsalias())){
                JSONArray addressArray = factJson.getJSONArray(attr);
                return addressArray.stream().allMatch(address -> compareAddress((JSONObject) address));
            }
            return compareAddress(factJson.getJSONObject(attr));
        }else if (Objects.equals(fieldType, FieldTypeEnum.CHECKBOX_GROUP.getType())
                || Objects.equals(fieldType, FieldTypeEnum.COMBO_CHECK.getType())
                || Objects.equals(fieldType, FieldTypeEnum.USER_GROUP.getType())
                || Objects.equals(fieldType, FieldTypeEnum.DEPT_GROUP.getType())
                || Objects.equals(fieldType, FieldTypeEnum.LABEL.getType())
                || Objects.equals(fieldType, FieldTypeEnum.LINK_DATA_MULTI.getType())
                || Objects.equals(fieldType, FieldTypeEnum.LINK_BUSINESS_MULTI.getType())
                || (attr.contains(FieldTypeEnum.SUB_FORM.getEsalias()) && attr.contains(StringConstant.POINT))
        ) {
            return StringUtils.isEmpty(value.toString()) || Objects.equals(value.toString(), "[]");
        } else {
            return StringUtils.isEmpty(value.toString());
        }
    }

    private boolean compareAddress(JSONObject address2){
        String addrStr = address2.values().stream().map(Object::toString).collect(Collectors.joining());
        return StringUtil.isEmpty(addrStr);
    }
}
